import { apiClient } from './client'

export interface ScreenInfo {
  screenWidth: number
  screenHeight: number
  devicePixelRatio: number
  userAgent: string
  viewportWidth: number
  viewportHeight: number
  orientation: 'portrait' | 'landscape'
  timestamp: number
}

export interface ScreenInfoResponse {
  code: number
  message: string
  data: ScreenInfo
}

/**
 * 屏幕信息服务
 * 提供获取屏幕尺寸、设备信息等功能的API
 */
export const screenService = {
  /**
   * 获取屏幕信息
   * @returns Promise<ScreenInfoResponse>
   */
  async getScreenInfo(): Promise<ScreenInfoResponse> {
    try {
      // 首先尝试从后端API获取
      const response = await apiClient.get<ScreenInfoResponse>('/api/screen/info')
      return response.data
    } catch (error) {
      console.warn('无法从后端API获取屏幕信息，使用本地信息:', error)
      
      // 如果API失败，返回本地屏幕信息
      return this.getLocalScreenInfo()
    }
  },

  /**
   * 获取本地屏幕信息（作为备用方案）
   * @returns ScreenInfoResponse
   */
  getLocalScreenInfo(): ScreenInfoResponse {
    const screenInfo: ScreenInfo = {
      screenWidth: window.screen.width,
      screenHeight: window.screen.height,
      devicePixelRatio: window.devicePixelRatio || 1,
      userAgent: navigator.userAgent,
      viewportWidth: window.innerWidth,
      viewportHeight: window.innerHeight,
      orientation: window.innerWidth > window.innerHeight ? 'landscape' : 'portrait',
      timestamp: Date.now()
    }

    return {
      code: 200,
      message: '使用本地屏幕信息',
      data: screenInfo
    }
  },

  /**
   * 获取当前视口宽度
   * @returns number
   */
  getCurrentViewportWidth(): number {
    return window.innerWidth
  },

  /**
   * 获取当前视口高度
   * @returns number
   */
  getCurrentViewportHeight(): number {
    return window.innerHeight
  },

  /**
   * 检查是否为移动设备
   * @returns boolean
   */
  isMobileDevice(): boolean {
    return window.innerWidth <= 768
  },

  /**
   * 检查是否为触摸设备
   * @returns boolean
   */
  isTouchDevice(): boolean {
    return 'ontouchstart' in window || navigator.maxTouchPoints > 0
  },

  /**
   * 获取设备方向
   * @returns 'portrait' | 'landscape'
   */
  getOrientation(): 'portrait' | 'landscape' {
    return window.innerWidth > window.innerHeight ? 'landscape' : 'portrait'
  }
}

export default screenService
